package com.example.layui.service;

import com.example.layui.config.SendConfig;
import com.example.layui.mapper.OrderMapper;
import com.example.layui.mapper.ProductDao;
import com.example.layui.pojo.Order;
import com.example.layui.pojo.Product;
import com.example.layui.pojo.User;
import com.example.layui.util.ResponseResult;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    OrderMapper orderMapper;
    @Resource
    SendConfig sendConfig;
    @Resource
    ProductDao productDao;
    @Autowired
    ProductService productService;

    @Override
    public void createOrder(int num, int pid) {
        Product product=productDao.getAllById(pid);
        Order order=new Order();
        //得到security登录用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        order.setUserId(user.getId());
        order.setUserPhone(user.getPhone());
        order.setProductNum(num);
        order.setProductName(product.getProductName());
        order.setProductPrice(product.getProductPrice().multiply(BigDecimal.valueOf(num)));
        order.setUserAddress(user.getAddress());
        order.setCreateDate(new Date());
        order.setCreateBy(user.getId());
        orderMapper.createOrder(order);
        product.setProductStack(product.getProductStack()-order.getProductNum());
        productService.updateProduct(product);
        //发送消息
        sendConfig.send(order);
    }

    @Override
    public Integer count(Order order,Integer bangkeId) {
        return orderMapper.count(order,bangkeId);
    }

    @Override
    public List<Order> queryByPage(Order order,Integer bangkeId, int from, Integer to) {
        return orderMapper.queryByPage(order,bangkeId,from,to);
    }

}
